import urllib.request

# 使用urllib获取百度首页源码

baidu_url = 'http://www.baidu.com'

headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) '
                  'Chrome/118.0.0.0 Safari/537.36 Edg/118.0.2088.76'
}

req = urllib.request.Request(url=baidu_url, headers=headers)

# 1、获取handler对象
handler = urllib.request.HTTPHandler()

# 2、获取opener对象
opener = urllib.request.build_opener(handler)

# 3、调用open方法
res = opener.open(req)

print(res.read().decode('utf-8'))